package com.micro.magupe.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import com.micro.magupe.auth.service.MicroUserDetailsService;

@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

	@Autowired
	private MicroUserDetailsService userDetailsService;
	
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    
    /**
     * 用户名密码和oauth2中的用户密码都要经过new BCryptPasswordEncoder().encode(password)
     * @return
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    /**
     * authorizeRequests: 确保我们应用中的所有请求都需要用户被认证
     * formLogin: 允许用户进行基于表单的认证
     *     permitAll: 允许所有用户访问
     *     loginPage: 指定登录页面
     *     failureUrl: 登录失败页面
     * httpBasic: 允许用户使用HTTP基本验证进行认证
     *     permitAll: 允许所有用户访问
     * 
     * anyRequest().authenticated(): 表示其他的请求都必须要有权限认证。 
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        	.csrf().disable()
        	.authorizeRequests().anyRequest().authenticated()
	        .and()
	        .formLogin()
	        .and()
	        .httpBasic();
    }
    
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/favor.ioc");
    }
}
